package com.cxt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cxt.context.BaseContext;
import com.cxt.dto.UserDto;
import com.cxt.entity.*;
import com.cxt.properties.JwtProperties;
import com.cxt.result.Result;
import com.cxt.service.*;
import com.cxt.utils.JwtUtil;
import com.cxt.vo.DirVo;
import com.cxt.vo.UserLonginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
//import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
//import java.util.List;
import java.util.Map;
import java.util.Random;

//import java.beans.Transient;

/**
 * 用户相关控制器
 *
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private IAccountInfoService accountInfoService;
    @Autowired
    private DriverInfoService driverInfoService;
    @Autowired
    private IMessageNotificationService messageNotificationService;
    @Autowired
    private VerificationCodeInfoService verificationCodeInfoService;
    @Autowired
    private StudentInfoService studentInfoService;

    /**
     * 验证码
     */
    @PostMapping("/sendCode")
    public Result sendCode(@RequestBody User user) {
        //
        LambdaQueryWrapper<VerificationCodeInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VerificationCodeInfo::getPhoneNumber, user.getPhone());
        verificationCodeInfoService.remove(queryWrapper);
        VerificationCodeInfo verificationCode = new VerificationCodeInfo();
        verificationCode.setPhoneNumber(user.getPhone());
        //随机4位数字
         Random random = new Random();
        int fourDigitRandomNumber = 1000 + random.nextInt(9000); // [1000, 9999]
        verificationCode.setVerificationCode(fourDigitRandomNumber+"");
        verificationCode.setCreatedAt(LocalDateTime.now());
        verificationCodeInfoService.save(verificationCode);
        log.info("----------------------验证码----------------------------------");
        log.info("------------"+fourDigitRandomNumber+"------------------------");
        log.info("---------------TODO：—————————————--------——————--------------");
        return Result.success();
    }
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDto user) {
        log.info("用户注册");
        if (user.getCode()==null) {
            return Result.error("验证码不能为空");
        }
        LambdaQueryWrapper<VerificationCodeInfo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(VerificationCodeInfo::getPhoneNumber, user.getPhone())
                .orderByDesc(VerificationCodeInfo::getCreatedAt)
                .ge(VerificationCodeInfo::getCreatedAt, LocalDateTime.now().minus(5, ChronoUnit.MINUTES)); // 限制为5分钟内的记录
        //最新的一条
        VerificationCodeInfo verificationCodeInfo = verificationCodeInfoService.getOne(queryWrapper);
        if(verificationCodeInfo==null||!user.getCode().equals(verificationCodeInfo.getVerificationCode())){
            return Result.error("验证码错误");
        }
        User user1=new User();
        user1.setPhone(user.getPhone());
        user1.setPassword(user.getPassword());
        boolean isRegister = userService.register(user1);
        if (!isRegister) {
            return Result.error("注册失败");
        }
        return Result.success("注册成功");
    }
    /**
     * 用户修改密码
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody UserDto user) {
        if (user.getCode()==null) {
        return Result.error("验证码不能为空");
        }
        LambdaQueryWrapper<VerificationCodeInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VerificationCodeInfo::getPhoneNumber, user.getPhone())
                .orderByDesc(VerificationCodeInfo::getCreatedAt)
                .ge(VerificationCodeInfo::getCreatedAt, LocalDateTime.now().minus(5, ChronoUnit.MINUTES)); // 限制为5分钟内的记录
        //最新的一条
        VerificationCodeInfo verificationCodeInfo = verificationCodeInfoService.getOne(queryWrapper);
        if(verificationCodeInfo==null||!user.getCode().equals(verificationCodeInfo.getVerificationCode())){
            return Result.error("验证码错误");
        }
        User user1=new User();
        LambdaQueryWrapper<User> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(User::getPhone,user.getPhone());
        user1 = userService.getOne(queryWrapper1);
        if (user1==null) {
            return Result.error("用户不存在");
        }
        user1.setId(user1.getId());
        user1.setPhone(user.getPhone());
        user1.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        boolean isUpdate = userService.updateById(user1);
        if (!isUpdate) {
            return Result.error("修改失败");
        }
        return Result.success();
    }
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        log.info("用户登录");
        User login = userService.login(user);
        if (login==null) {
            return Result.error("登录失败");
        }
        Map<String,Object> claims= new HashMap<>();
        claims.put(jwtProperties.getUserIdName(),login.getId());
        String token= JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        UserLonginVo userLonginVo = UserLonginVo.fromUserAndToken(login, token);
        return Result.success(userLonginVo);
    }
    /**
     * 用户获取个人信息
     */
    @GetMapping("/getUserInfo")
    public Result getUser() {
        log.info("用户获取个人信息");
        User user = userService.getById(BaseContext.getCurrentId());
        user.setPassword(null);
        return Result.success(user);
    }
    /**
     * 用户修改个人信息
     */
    @PostMapping("/updateUserInfo")
    public Result updateUser(@RequestBody User user) {
        log.info("用户修改个人信息");
        User user1 = new User();
        user1.setId(BaseContext.getCurrentId());
        user1.setNickname(user.getNickname());
        user1.setAvatarUrl(user.getAvatarUrl());
        boolean isUpdate = userService.updateById(user1);
        if (!isUpdate) {
            return Result.error("修改失败");
        }
        return Result.success();
    }
    /**
     * 绑定学生信息
     */
    @PostMapping("/bindStudentInfo")
    public Result bindStudentInfo(@RequestBody StudentInfo studentInfo) {
        log.info("绑定学生信息");
        boolean isBind = userService.bindStudentInfo(studentInfo);
        if (!isBind) {
            return Result.error("绑定失败");
        }
        return Result.success();
    }
    /**
     * 获取用户学生信息
     */
    @GetMapping("/getStudentInfo")
    public Result getStudentInfo() {
        log.info("获取用户学生信息");
        StudentInfo studentInfo = userService.getStudentInfo();
        return Result.success(studentInfo);
    }
    /**
     * 更改学生信息
     */
    @PostMapping("/updateStudentInfo")
    public Result updateStudentInfo(@RequestBody StudentInfo studentInfo) {
        log.info("更改学生信息");
        boolean isUpdate = userService.updateStudentInfo(studentInfo);
        if (!isUpdate) {
            return Result.error("修改失败");
        }
        return Result.success();
    }
    /**
     * 司机认证添加
     */
    @PostMapping("/addDriverInfo")
    public Result addDriverInfo(@RequestBody DriverInfo driverInfo) {
        log.info("司机认证添加");
        boolean isAdd = userService.addDriverInfo(driverInfo);
        if (!isAdd) {
            return Result.error("添加失败");
        }
        accountInfoService.addAccountInfo(driverInfo.getUserId());
        return Result.success();
    }
    /**
     * 司机认证状态获取
     */
    @GetMapping("/getDriverInfoStatus")
    public Result getDriverInfoStatus() {
        log.info("司机认证状态获取");
        Integer status = userService.getDriverInfoStatus();
        return Result.success(status);
    }
    /**
     * 司机认证修改
     */
    @PostMapping("/updateDriverInfo")
    public Result updateDriverInfo(@RequestBody com.cxt.entity.DriverInfo driverInfo) {
        log.info("司机认证修改");
        boolean isUpdate = userService.updateDriverInfo(driverInfo);
        if (!isUpdate) {
            return Result.error("修改失败");
        }
        return Result.success();
    }
    /**
     * 司机认证信息
     */
    @GetMapping("/getDriverInfo")
    public Result getDriverInfo() {
        log.info("司机认证信息");
        DriverInfo driverInfo = userService.getDriverInfo();
        return Result.success(driverInfo);
    }
    /**
     * 司机审核列表
     */
    @GetMapping("/getDriverAuditList")
    public Result getDriverAuditList() {
        log.info("司机审核列表");
        List<DriverInfo> driverInfoList = driverInfoService.list();
        return Result.success(driverInfoList);
    }
    /**
     * 司机审核处理
     */
    @PostMapping("/driverAudit")
    @Transactional
    public Result driverAudit(@RequestBody DriverInfo driverInfo){
        log.info("司机审核处理");
        //司机资质更新
        boolean isUpdate = driverInfoService.updateById(driverInfo);
        //如果是通过的话
        if (driverInfo.getStatus()==1) {
            //账户信息更新
            User byId = userService.getById(driverInfo.getUserId());
            byId.setIsDriver(true);
            messageNotificationService.addMassage(driverInfo.getUserId(),"您的司机认证已通过，请保持接驾");
            userService.updateById(byId);
        }
        if (driverInfo.getStatus()==2) {
            //账户信息更新
            User byId = userService.getById(driverInfo.getUserId());
            byId.setIsDriver(false);
            messageNotificationService.addMassage(driverInfo.getUserId(),"您的司机认证未通过，请重新认证");
            userService.updateById(byId);
        }
        if (!isUpdate) {
            return Result.error("修改失败");
        }
        return Result.success();
    }
    /**
     * 获取司机信息
     */
    @GetMapping("/getDriverInfoById")
    public Result getDriverInfo(Long id) {
        log.info("获取司机信息");
        User byId = userService.getById(id);
        LambdaQueryWrapper<DriverInfo> query = new LambdaQueryWrapper<>();
        query.eq(DriverInfo::getUserId,id);
        DriverInfo driverInfo = driverInfoService.getOne(query);
        DirVo dao = DirVo.builder().user(byId).driverInfo(driverInfo).build();
        return Result.success(dao);
    }
    /**
     * 账户信息
     */
    @GetMapping("/getAccountInfo")
    public Result getAccountInfo() {
        log.info("账户信息");
        AccountInfo accountInfo = accountInfoService.getAccountInfo();
        return Result.success(accountInfo);
    }
    /**
     * 账户修改
     */
    @PostMapping("/updateAccountInfo")
    public Result updateAccountInfo(@RequestBody AccountInfo accountInfo) {
        log.info("账户修改");
        boolean isUpdate = accountInfoService.updateAccountIfo(accountInfo);
        if (!isUpdate) {
            return Result.error("修改失败");
        }
        return Result.success();
    }
    /**
     * 账户提现
     */
    @GetMapping("/withdraw")
    public Result withdraw(Double deduction) {
        log.info("账户提现");
        boolean isWithdraw = accountInfoService.withdraw(deduction);
        if (!isWithdraw) {
            return Result.error("提现失败");
        }
        return Result.success();
    }
    /**
     * 账户账单
     */
    @GetMapping("/getBillInfo")
    public Result getBillInfo() {
        log.info("账户账单");
        List<BillInfo> billInfo = accountInfoService.getBillInfo();
        return Result.success(billInfo);
    }
    /**
     * 根据ids查询用户昵称和头像
     */
    @GetMapping("/getUserNicknameAndAvatar")
    public Result getUserNicknameAndAvatar(@RequestParam  List<Long> ids) {
        log.info("根据ids查询用户昵称和头像");
        List<User> users = userService.listByIds(ids);
        //只保留昵称和头像
        users.forEach(user -> {
            user.setPassword(null);
            user.setPhone(null);
            user.setIsDriver(null);
            user.setIsBoundStudentInfo(null);
            user.setCreateTime(null);
            user.setUpdateTime(null);
            user.setCreateUser(null);
            user.setUpdateUser(null);
        });
        return Result.success(users);
    }
    /**
     * 添加用户信息表
     */
    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {
        log.info("添加用户信息表");
        boolean isAdd = userService.save(user);
        if (!isAdd) {
            return Result.error("添加失败");
        }
        return Result.success();
    }
    /**
     * 根据id删除用户信息表
     */
    @GetMapping("/delete")
    public Result deleteUser(Integer id) {
        log.info("删除用户信息表,id:{}", id);
        boolean isDelete = userService.removeById(id);
        if (!isDelete) {
            return Result.error("删除失败");
        }
        return Result.success("删除成功");
    }

    /**
     * getAll
     */
    @GetMapping("/getAllAdmin")
    public Result getAll() {
        log.info("获取所有用户信息表");
        List<User> list = userService.list();
        return Result.success(list);
    }
    /**
     * 修改用户信息
     */
    @PostMapping("/updateAdmin")
    public Result updateUserAdmin(@RequestBody User user) {
        log.info("修改用户信息");
        boolean isUpdate = userService.updateById(user);
        if (!isUpdate) {
            return Result.error("修改失败");
        }
        return Result.success();
    }

    /**
     * 返回所有学生信息
     */
    @GetMapping("/getStudent")
    public Result getStudent(){
        log.info("获取所有学生信息");
        List<StudentInfo> studentInfos = userService.getAllStudent();
        return Result.success(studentInfos);
    }
    /**
     * 把学生信息绑定取消了
     */
    @GetMapping("/cancelBindStudentInfo")
    public Result cancelBindStudentInfo(Long userId) {
        log.info("取消绑定学生信息");
        //获取当前用户的studentInfo
        LambdaQueryWrapper<StudentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentInfo::getUserId, userId);
        StudentInfo one = studentInfoService.getOne(queryWrapper);
        if (one == null) {
            return Result.error("没有绑定学生信息");
        }
        //删除
        boolean remove = studentInfoService.remove(queryWrapper);
        User byId = userService.getById(userId);
        byId.setIsBoundStudentInfo(false);
        userService.updateById(byId);
        if (!remove) {
            return Result.error("取消绑定失败");
        }
        return Result.success("取消绑定成功");
    }

}
